package org.classg.msm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.classg.msm.service.MsmService;
import org.classg.utils.R;
import org.classg.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(description = "阿里云短信服务")
@RestController
@RequestMapping("/msmservice")
@CrossOrigin
public class MsmController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MsmService msmService;

    @ApiOperation("根据手机号发送短信验证码")
    @GetMapping("/sendMsmCode/{phone}")
    public R sendMsmCode(@ApiParam(name = "phone", value = "手机号码", required = true) @PathVariable String phone) {
        // 查询redis内存中是否有手机号
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {return R.ok();}

        // 生成6位数的随机验证码
        code = RandomUtil.getSixBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        Boolean isSend = msmService.sendMsmCode(phone, param);
        if (isSend) {
            // 把数据放入redis中，同时设置有效时长
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败！");
        }
    }

//    @GetMapping("/sendMsmCode/{phone}")
//    public R test01(@PathVariable String phone) {
//        System.out.println("test01======="+phone);
//        return R.ok();
//    }
}
